package com.raysdata.smartcity.flow.activiti.web;

import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.Key;
import com.raysdata.smartcity.dao.sys.OrgDao;
import com.raysdata.smartcity.dto.Organization;
import com.raysdata.smartcity.dto.User;
import com.raysdata.smartcity.flow.activiti.dao.ProcessDao;
import com.raysdata.smartcity.web.BaseController;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.impl.ProcessEngineImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 流程控制器
 * Created by liux on 2017/03/06.
 */
@Controller
@RequestMapping(value = "/process")
public class ProcessController extends BaseController {
    @Autowired
    public ProcessEngine processEngine ;
    @Autowired
    public ProcessDao processDao;
    /**
     * 创建流程实例
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/createProcessInstance")
    public void createProcessInstance(HttpServletRequest request, HttpServletResponse response) {

        String judgeApplyId = request.getParameter("judge_apply_id");
        String taskTitle = request.getParameter("taskTitle");

        //获取当前登录人信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("LoginUser");

        String approveUsers="";
        String approveResult="0";

        //日志信息
        String content="申请研判："+taskTitle;
        String type= Key.LOG_APPROVE;
        String processInstanceId="";

        //获取当前登录人所属单位
        Organization org=orgDao.getParentOrg(user.getOrg_id());

        //判断是否是市级申请
        if("1".equals(org.getLevel())){
            approveResult="1";
            //市局申请下一环节处理人 为市局值班长
            List<User> users=userDao.getUserByOrgAndRole(Key.NODEROLE_SJZBZ,org.getOrg_code());
            for(User u:users){
                approveUsers+=u.getLogin_name()+",";
            }
        }else{
            Organization o=orgDao.getOrgById(user.getOrg_id());
            //非市局申请下一环节处理人 为所长/大队长
            List<User> users=userDao.getUserByOrgAndRole(Key.NODEROLE_SZ,o.getOrg_code());
            for(User u:users){
                approveUsers+=u.getLogin_name()+",";
            }
        }

        try {
            //获取流程定义
            //FormFlow flow = formFlowDao.getFlowByForm(order_type);

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sendPerson", user.getLogin_name());
            map.put("taskTitle", taskTitle);
            map.put("nextNode", approveResult);

            if (("".equals(approveUsers) || approveUsers == null)) {

                HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"申请失败！\"}");

            } else {
                //approveUsers=approveUsers.substring(0,approveUsers.length()-1);

                map.put("approveUsers", approveUsers);

                //启动流程实例
                processInstanceId=processDao.createProcessInstance(Key.YP_APPLY_FLOW_V2, Key.YP_APPLY_TABLE, map,user.getLogin_name());

                //保存流程实例到业务表
               // judgeApplyDao.updProcInstId(judgeApplyId,processInstanceId);
                //更新业务表中的状态为审批中
               // judgeApplyDao.updJudgeApplyStatus(Key.APPLY_TYPE_TR,judgeApplyId);


                //插入邮件池
                /*List<User> userList=new ArrayList<>();
                if (!"".equals(approve_group) && approve_group != null) {
                     userList = userGroupDao.getUsersByGroupId(approve_group);
                }
                if (!"".equals(approve_user) && approve_user != null) {
                    User user1 = userDao.getUserByLoginName(approve_user);
                    userList.add(user1);
                }
                if(userList.size()>0){
                    for(User u:userList){
                        if(u.getEmail()!=null&&!u.getEmail().equals("")){
                            String subject="睿至综合业务管理平台有任务等待您处理！";
                            String context="任务标题："+taskTitle+"\n\n派发人："+user.getUser_name()+"\n\n\n\n请您登录睿至综合业务管理平台及时处理！";
                            EmailPool emailPool = new EmailPool();
                            emailPool.setEmail_pool_id(UUID.randomUUID().toString().trim().replaceAll("-", ""));
                            emailPool.setCperson(user.getLogin_name());
                            emailPool.setEmail_addr(u.getEmail());
                            emailPool.setEmail_comment(context);
                            emailPool.setEmail_title(subject);
                            emailPool.setMsg_type(order_type);
                            emailPool.setStatus("0");
                            emailPoolDao.insEmail_pool(emailPool);
                        }
                    }
                }*/
                logDao.saveLog(request,content,type,user,processInstanceId, Key.LOG_SUCCESS);
                HelperClazz.renderJson(response, "{\"success\":true,\"msg\":\"申请成功！\"}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logDao.saveLog(request,content,type,user,processInstanceId, Key.LOG_ERROR);
            HelperClazz.renderJson(response, "{\"success\":false,\"msg\":\"申请失败！\"}");
        }
    }

    /**
     * 展示流程图片
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/viewCurrentImage")
    public String viewCurrentImage(HttpServletRequest request, HttpServletResponse response){
        String proc_def_id = request.getParameter("proc_def_id");
        String proc_inst_id = request.getParameter("proc_inst_id");
        ProcessDefinition pd = processDao.getProcessDefinitionById(proc_def_id);
        // 获取流程部署ID
        request.setAttribute("deploymentId", pd.getDeploymentId());
        // 获取流程图片的名称
        request.setAttribute("imageName", pd.getDiagramResourceName());

        // 获取当前活动的坐标
        Map<String,Object> currentActivityCoordinates =processDao.getCurrentActivityCoordinates(proc_def_id,proc_inst_id);
        request.setAttribute("acs", currentActivityCoordinates);
        return "crm/flowForm/processimage";
    }


    @RequestMapping(value = "/viewImage")
    public String viewImage(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String deploymentId = request.getParameter("deploymentId");
        String imageName = request.getParameter("imageName");

        //imageName=URLDecoder.decode(imageName,"UTF-8");
        imageName=new String(imageName.getBytes("ISO-8859-1"),"UTF-8");
        //获取图片的输入流
        InputStream in = processEngine.getRepositoryService().getResourceAsStream(deploymentId, imageName);
        try {
            OutputStream out = response.getOutputStream();
            // 把图片的输入流程写入resp的输出流中
            byte[] b = new byte[1024];
            for (int len = -1; (len= in.read(b))!=-1; ) {
                out.write(b, 0, len);
            }
            // 关闭流
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取流程图
     * @param request
     * @param response
     */
    @RequestMapping(value = "/bpmnView")
    public void bpmnView(HttpServletRequest request,HttpServletResponse response) {

        // 设置页面不缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        try {

            String proc_def_id = request.getParameter("proc_def_id");
            String instanceId = request.getParameter("proc_inst_id");

            Map<String,Object> map=processDao.getActivityCoordinates(proc_def_id,instanceId);
            // 设置图片的字体
            ProcessEngineImpl defaultProcessEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
            // 有中文的话防止图片中出现乱码，否则会显示类似于“□”这样的字
            defaultProcessEngine.getProcessEngineConfiguration().setActivityFontName("宋体");
            defaultProcessEngine.getProcessEngineConfiguration().setLabelFontName("宋体");
            Context.setProcessEngineConfiguration(defaultProcessEngine.getProcessEngineConfiguration());

            ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
            // activitiIds就是标亮走过的节点 flowIds就是标亮走过的线
            InputStream imageStream = processDiagramGenerator.generateDiagram((BpmnModel)map.get("bpmnModel"),"png",(List)map.get("activitiIds"),(List)map.get("flowIds")
                    ,defaultProcessEngine.getProcessEngineConfiguration().getActivityFontName().toString(),defaultProcessEngine.getProcessEngineConfiguration().getLabelFontName().toString()
                    ,null,null,1.0);
            response.setContentType("image/png");

            OutputStream os = response.getOutputStream();
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = imageStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            imageStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            //throw new RuntimeException("获取流程图异常!");
        }
    }


    /**
     * 删除流程实例--开发测试专用
     * @param request
     * @param response
     */
/*    @RequestMapping(value = "/hi")
    public void hi(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        runtimeService.deleteProcessInstance(id, "");
    }*/



}
